package com.itcast.rpc.client.connector;

import com.itcast.common.utils.SpringBeanFactory;
import com.itcast.rpc.client.channel.ChannelHolder;
import com.itcast.rpc.client.channel.ProviderService;
import com.itcast.rpc.client.runner.RpcRequestManager;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;

public class RpcClientConnector implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(RpcClientConnector.class);
    private String requestId;
    private ProviderService providerService;
    private CountDownLatch latch;
    private RpcClientInitializer znsClientInitializer;

    public RpcClientConnector(String requestId, ProviderService providerService,
                              CountDownLatch latch) {
        this.requestId = requestId;
        this.providerService = providerService;
        this.latch = latch;
        this.znsClientInitializer = SpringBeanFactory.getBean(RpcClientInitializer.class);
    }

    @Override
    public void run() {
// 1. 创建Netty连接配置
        EventLoopGroup worker = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(worker)
                .channel(NioSocketChannel.class)
                .remoteAddress(providerService.getServerIp(), providerService.getNetworkPort())
                .handler(znsClientInitializer);
        try {
// 2. 建立连接
            ChannelFuture future = bootstrap.connect().sync();
            if (future.isSuccess()) {
                ChannelHolder channelHolder = ChannelHolder.builder()
                        .channel(future.channel())
                        .eventLoopGroup(worker)
                        .build();
                // 将对应的请求（requestId）的ChannelHolder对象
                RpcRequestManager.registerChannelHolder(requestId,channelHolder);

            }
            latch.countDown();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
}
